<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-row>
        <el-col>
          <el-form-item label="门店名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入门店名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-120px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="合作等级" prop="cooperationDegree">
            <el-select
              v-model="queryParams.cooperationDegree"
              placeholder="请选择"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_COOPERATION_DEGREE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态" prop="checkState">
            <el-select
              v-model="queryParams.checkState"
              placeholder="请选择审批状态"
              clearable
              class="!w-160px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px"/>
              搜索
            </el-button>
          </el-form-item>

          <el-form-item>

            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px"/>
              重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['erp:merchant:create']"
            >
              <Icon icon="ep:plus" class="mr-5px"/>
              新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['erp:merchant:export']"
            >
              <Icon icon="ep:download" class="mr-5px"/>
              导出
            </el-button>
          </el-form-item>

        </el-col>

      </el-row>


    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table border v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="编号" align="center" prop="id"/>-->
      <el-table-column label="门店名称" prop="name" min-width="200px">
        <template #default="scope">
          <!--    归属省份+归属城市+归属区+名称       -->

          <!--          {{ scope.row.belongProvince }}{{ scope.row.belongCity }}{{ scope.row.belongDistrict }}-->
          <!--          名称在添加时 拼接保存省市区-->
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contact" min-width="200px"/>
      <el-table-column label="手机号" align="center" prop="mobile" min-width="200px"/>
      <el-table-column label="审批状态" align="center" prop="checkState" min-width="150">
        <template #default="scope">
          <div
            :class="['custom-select', { 'priorit1' : scope.row.checkState === 0 || scope.row.checkState === 3,
          'priorit2' : scope.row.checkState === 1 || scope.row.checkState === 4,
          'priorit3' : scope.row.checkState === 2 || scope.row.checkState === 5}]">
            <el-select style="text-align: center;"
                       @change="handleMerchantCheckStateChange(scope.row)"
                       v-model="scope.row.checkState">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="省份" align="center" prop="belongProvince"/>
      <el-table-column label="城市" align="center" prop="belongCity"/>
      <el-table-column label="区" align="center" prop="belongDistrict"/>
      <el-table-column label="地址" align="center" prop="belongAddress" min-width="200px"/>
      <!--      <el-table-column label="联系电话" align="center" prop="telephone" />-->
      <!--      <el-table-column label="电子邮箱" align="center" prop="email" />-->

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="纳税人识别号" align="center" prop="taxNo" min-width="140px"/>
      <!--      <el-table-column label="税率" align="center" prop="taxPercent"/>-->
      <el-table-column label="开户行" align="center" prop="bankName" min-width="120px"/>
      <el-table-column label="开户账号" align="center" prop="bankAccount" min-width="120px"/>
      <el-table-column label="开户地址" align="center" prop="bankAddress" min-width="120px"/>

      <el-table-column label="合作等级" align="center" prop="cooperationDegree" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_COOPERATION_DEGREE"
                    :value="scope.row.cooperationDegree"/>
        </template>
      </el-table-column>

      <!--      <el-table-column label="门店经度" align="center" prop="longitude" />-->
      <!--      <el-table-column label="门店纬度" align="center" prop="latitude" />-->
      <el-table-column label="结算类型" align="center" prop="settleType" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_SETTLE_TYPE" :value="scope.row.settleType"/>
        </template>
      </el-table-column>
      <el-table-column label="是否开票" align="center" prop="hasInvoice" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_HAS_INVOICE" :value="scope.row.hasInvoice"/>
        </template>
      </el-table-column>
      <el-table-column label="开票类型" align="center" prop="invoiceType" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_INVOICE_TYPE" :value="scope.row.invoiceType"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" width="200px" align="center" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:merchant:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="merchantAttendanceItemShow(scope.row)"
            v-hasPermi="['erp:merchant:update']"
          >
            假勤明细
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:merchant:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MerchantForm ref="formRef" @success="getList"/>


  <el-dialog :title="merchantAttendanceItemTitle" v-model="merchantAttendanceItemVisible"
             width="50%">
    <el-table v-loading="loading" :data="merchantAttendanceItemList" row-key="id">
      <el-table-column label="序号" align="center" width="60px" prop="id"/>
      <el-table-column label="月份" align="center">
        <template #default="scope">
          <el-date-picker
            class="!w-180px"
            v-if="!scope.row.id"
            v-model="scope.row.month"
            type="month"
            placeholder="选择年月"
            format="YYYY-MM"
            value-format="YYYY-MM"/>
          <span v-else>
                {{ scope.row.month }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="上班时间" align="center">
        <template #default="scope">
          <el-time-picker class="!w-180px" v-if="!scope.row.id"
                          v-model="scope.row.dayWorkingTimeArray" is-range range-separator="至"
                          format="HH:mm"/>
          <span v-else>
            <el-time-picker class="!w-180px" v-if="scope.row.id" disabled
                            v-model="scope.row.dayWorkingTimeArray" is-range range-separator="至"
                            format="HH:mm"/>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="月休息天数" align="center">
        <template #default="scope">
          <el-input-number v-if="!scope.row.id" class="!w-100px" v-model="scope.row.monthRestDays"
                           :min="1" :max="10" placeholder="请输入月休息天数"/>
          <span v-else> {{ scope.row.monthRestDays }} </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150px">
        <template #default="scope">
          <el-button type="primary" size="small" v-if="!scope.row.id"
                     @click.stop="handleSaveMA(scope.row)">保存
          </el-button>
          <el-button type="danger" size="small" v-if="scope.row.id"
                     @click.stop="handleDelMA(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <el-button type="success" @click="addLineData">添加月份假勤</el-button>
    </div>
  </el-dialog>

</template>

<script setup lang="ts">
import {getStrDictOptions, getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {MerchantApi, MerchantVO} from '@/api/erp/merchant'
import {MerchantAttendanceApi, MerchantAttendanceVO} from '@/api/erp/merchant/attendance'
import MerchantForm from './MerchantForm.vue'
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {ReimburseApi} from "@/api/erp/finance/reimburse";

/** 派单系统 门店 列表 */
defineOptions({name: 'Merchant'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const merchantAttendanceItemVisible = ref(false)
const merchantAttendanceItemList = ref([{id: 0, dayWorkingTimeArray: [new Date(), new Date()]}])
const merchantAttendanceItemTitle = ref()
const merchantAttendanceId = ref()

const loading = ref(true) // 列表的加载中
const list = ref<MerchantVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// const monthOptions = ref([
//   {value: '1', label: '一月',},  {value: '2', label: '二月',},  {value: '3', label: '三月',},
//   {value: '4', label: '四月',},  {value: '5', label: '五月',},  {value: '6', label: '六月',},
//   {value: '7', label: '七月',},  {value: '8', label: '八月',},  {value: '9', label: '九月',},
//   {value: '10', label: '十月',},  {value: '11', label: '十一月',},  {value: '12', label: '十二月',},
// ])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  contact: undefined,
  mobile: undefined,
  telephone: undefined,
  email: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  taxNo: undefined,
  taxPercent: undefined,
  bankName: undefined,
  bankAccount: undefined,
  bankAddress: undefined,
  createTime: [],
  cooperationDegree: undefined,
  belongProvince: undefined,
  belongCity: undefined,
  belongDistrict: undefined,
  belongAddress: undefined,
  longitude: undefined,
  latitude: undefined,
  settleType: undefined,
  hasInvoice: undefined,
  invoiceType: undefined,
  dayRestTime: undefined,
})

const attendanceQueryParams = reactive({
  merchantId: undefined,
  monthRestDays: undefined,
  dayWorkingTime: undefined,
  dayRestTime: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MerchantApi.getMerchantPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleMerchantCheckStateChange = async (row) => {

  const merchantCheckOptions = getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE);

  for (const key in merchantCheckOptions) {
    if (merchantCheckOptions[key].value === row.checkState) {

      await ElMessageBox.confirm(
        '商户【' + row.name + '】审批状态是否修改为【' + merchantCheckOptions[key].label + '】?',
        '审批状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await MerchantApi.updateMerchantCheckState(row.id, row.checkState);
            ElMessage({
              type: 'success',
              message: '审批状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }

}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MerchantApi.deleteMerchant(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MerchantApi.exportMerchant(queryParams)
    download.excel(data, '派单系统 门店.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const merchantAttendanceSubmit = async () => {
  let id = merchantAttendanceId.value;

  //搜索中 提示
  let loading = ElLoading.service({
    lock: true,
    text: '搜索中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await MerchantAttendanceApi.getMerchantAttendanceList(id).then(res => {
      merchantAttendanceItemList.value = res;
    })
  } finally {
    loading.close();
  }

}

const addLineData = async (row) => {
  const newData = {
    month: '1',
    monthRestDays: 1,
    dayWorkingTimeArray: []
  };
  merchantAttendanceItemList.value.push(newData);
}

const handleSaveMA = async (row) => {
  ElMessageBox.confirm("确认保存该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    row.merchantId = merchantAttendanceId;
    row.sort = 0;
    MerchantAttendanceApi.createMerchantAttendance(row)
    message.success(t('common.createSuccess'))
    merchantAttendanceSubmit();
  });
}

const handleDelMA = async (row) => {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    MerchantAttendanceApi.deleteMerchantAttendance(row.id)
    message.success(t('common.delSuccess'))
    merchantAttendanceSubmit();
  });

}

const merchantAttendanceItemShow = async (row) => {
  merchantAttendanceItemTitle.value = "【" + row.name + "】假勤设置明细";
  merchantAttendanceItemVisible.value = true;
  merchantAttendanceId.value = row.id;
  merchantAttendanceSubmit();
}


/** 初始化 **/
onMounted(() => {
  getList()
})
const route = useRoute();
onActivated(() => {
  //快捷添加
  let query = route.query;
  if (query.doType == 'handAdd') {
    formRef.value.open("create");
  }
  getList();
});

</script>
